<?php

namespace app\common\model;

use think\Db;
use think\Model;

/**
 * 会员余额日志模型
 */
class MoneyLog extends Model
{

    // 表名
    protected $name = 'user_money_log';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    // 追加属性
    protected $append = [];

    public static function getMoneyType()
    {
        return [
            100 => '直推收益',
            101 => '间推收益',
            201 => '提现',
            202 => '提现失败',
        ];
    }
    /**
     * Notes:记录会员账户流水，如果变动类型是成长值，且是增加的，则调用更新会员等级方法。该方法应在添加用户账户后调用
     * @author: cjh 2020/12/15 11:49
     * @param int $user_id  用户id
     * @param float $amount 变动数量
     * @param int $change_type  变动类型：1-减少；2-增加
     * @param int $source_type 来源类型
     * @param string $source_id 来源id
     * @param string $source_sn 来源单号
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function income($user_id, $amount, $change_type, $source_type, $source_sn = '')
    {
        $user = new User;
        $user = $user->get($user_id);
        if (empty($user)) {
            return false;
        }
        $before = $user->money ?? 0;
        if ($change_type == 1) {
            $user->setDec('money', $amount);
            $amount = -$amount;
        } else {
            $user->setInc('money', $amount);
        }
        $list =  self::getMoneyType();
        $left_amount = $user->money;
        $account_log = new self;
        $data['type'] = $change_type;
        $data['order_sn'] = $source_sn;
        $data['user_id'] = $user_id;
        $data['money'] = $amount ?? 0;
        $data['before'] = $before ?? 0;
        $data['after'] = $left_amount ?? 0;
        $data['memo'] = isset($list[$source_type]) ? $list[$source_type] : '';
        $data['source_type'] = $source_type;
        $account_log->allowField(true)->save($data);
        return true;
    }

    public static function subcommission($user, $money, $sn)
    {
        Db::startTrans();
        try {
            if ($user->pid) {
                // 直推收益
                $first = bcmul($money, config('site.direct'), 2);
                self::income($user->pid, $first, 2, 100, $sn);
                $pUser = User::get($user->pid);
                if ($pUser && $pUser->pid) {
                    //间推收益
                    $two = bcmul($money, config('site.extrapolation'), 2);
                    self::income($pUser->pid, $two, 2, 101, $sn);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            exception($e->getMessage());
            //throw $th;
        }
        return true;
    }
}
